<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Brownian Motion Balls</title>
    <style>
      #container {
        position: relative;
        width: 100%;
        height: 100vh;
        background-color: #f0f0f0;
      }

      .ball {
        position: absolute;
        border-radius: 50%;
        background-color: #333;
      }
    </style>
  </head>
  <body>
    <div id="container"></div>
    <script>
      const container = document.getElementById("container");
      const numberOfBalls = 100;
      const ballSize = 10;
      class Ball {
        // 当这个类被实例化后赋给初始值
        constructor() {
          this.x = Math.random() * (container.offsetWidth - ballSize);
          this.y = Math.random() * (container.offsetHeight - ballSize);
          this.vx = (Math.random() - 0.5) * 2;
          this.vy = (Math.random() - 0.5) * 2;
          this.element = document.createElement("div");
          this.element.className = "ball";
          this.element.style.width = `${ballSize}px`;
          this.element.style.height = `${ballSize}px`;
          this.element.style.left = `${this.x}px`;
          this.element.style.top = `${this.y}px`;
          container.appendChild(this.element);
        }
        update() {
          this.x += this.vx;
          this.y += this.vy;
          // Reverse direction if ball hits the container boundary
          if (this.x < 0 || this.x > container.offsetWidth - ballSize) {
            this.vx *= -1;
          }
          if (this.y < 0 || this.y > container.offsetHeight - ballSize) {
            this.vy *= -1;
          }
          this.element.style.left = `${this.x}px`;
          this.element.style.top = `${this.y}px`;
        }
      }
      const balls = [];
      for (let i = 0; i < numberOfBalls; i++) {
        balls.push(new Ball());
      }
      // console.log(balls);
      function animate() {
        balls.forEach((ball) => ball.update());
        requestAnimationFrame(animate);
      }
      animate();
    </script>
  </body>
</html>
